﻿#include "FiberMgr.h"

FiberMgr::FiberMgr(void)
:main_fiber_(NULL)
,fibers_()
,die_fibers_()
{
	main_fiber_ = ConvertThreadToFiber(NULL);
}

FiberMgr::~FiberMgr(void)
{
	for(Fibers::iterator i = die_fibers_.begin(); i != die_fibers_.end(); ++i)
	{
		deleteFiber(*i);
	}
	ConvertFiberToThread();
}

FiberMgr& FiberMgr::instance()
{
	static FiberMgr mgr;
	return mgr;
}

void FiberMgr::onFrame()
{
	for(Fibers::iterator i = die_fibers_.begin(); i != die_fibers_.end(); ++i)
	{
		deleteFiber(*i);
	}
	die_fibers_.clear();

	for(Fibers::iterator i = fibers_.begin(); i != fibers_.end(); ++i)
	{
		SwitchToFiber(*i);
	}
}

FiberMgr::FiberID FiberMgr::createFiber(FiberProc proc, LPVOID args)
{
	FiberID fid = CreateFiber(0, proc, args);
	fibers_.push_back(fid);
	return fid;
}

void FiberMgr::deleteFiber(FiberMgr::FiberID fid)
{
	DeleteFiber(fid);
	fibers_.remove(fid);
}

void FiberMgr::switchToFiber(FiberMgr::FiberID fid)
{
	SwitchToFiber(fid);
}

void FiberMgr::switchToMainFiber()
{
	SwitchToFiber(main_fiber_);
}

void FiberMgr::endFiber(FiberID fid)
{
	die_fibers_.push_back(fid);
	FiberMgr::instance().switchToMainFiber();
}

void FiberMgr::loop(int interval)
{
	while(true)
	{
		onFrame();
		Sleep(interval);
	}
	
}
